package com.payment.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.constant.Constants;
import com.payment.common.support.Convert;
import com.payment.common.type.MoneyTypeStatus;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.StringUtils;
import com.payment.common.utils.pay.EncryptUtil;
import com.payment.common.utils.push.JPushUtil;
import com.payment.system.domain.*;
import com.payment.system.mapper.*;
import com.payment.system.service.IMoneyChangeService;
import com.payment.system.vo.AppMoneyChangeVo;
import com.payment.system.vo.MoneyChangeNewOederVo;
import com.payment.system.vo.MoneyChangeVo;
import com.payment.system.vo.ProfitVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资金变动 服务层实现
 *
 * @author payment
 * @date 2019-01-08
 */
@Service
public class MoneyChangeServiceImpl implements IMoneyChangeService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MoneyChangeServiceImpl.class);

    @Autowired
    private MoneyChangeMapper moneyChangeMapper;
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private SystemConfigMapper configMapper;
    @Autowired
    private ShoppingProductMapper shoppingProductMapper;
    @Autowired
    private MerchantWalletMapper merchantWalletMapper;
    @Autowired
    private CompanyMoneyChangMapper companyMoneyChangMapper;
    @Autowired
    private MerchantParentMapper merchantParentMapper;

    /**
     * 查询资金变动信息
     *
     * @param iD 资金变动ID
     * @return 资金变动信息
     */
    @Override
    public MoneyChange selectMoneyChangeById(String iD) {
        return moneyChangeMapper.selectMoneyChangeById(iD);
    }

    /**
     * 查询资金变动列表
     *
     * @param moneyChange 资金变动信息
     * @return 资金变动集合
     */
    @Override
    public List<MoneyChange> selectMoneyChangeList(MoneyChange moneyChange) {
        return moneyChangeMapper.selectMoneyChangeList(moneyChange);
    }

    /**
     * 新增资金变动
     *
     * @param moneyChange 资金变动信息
     * @return 结果
     */
    @Override
    public int insertMoneyChange(MoneyChange moneyChange) {
        return moneyChangeMapper.insertMoneyChange(moneyChange);
    }

    /**
     * 修改资金变动
     *
     * @param moneyChange 资金变动信息
     * @return 结果
     */
    @Override
    public int updateMoneyChange(MoneyChange moneyChange) {
        return moneyChangeMapper.updateMoneyChange(moneyChange);
    }

    /**
     * 删除资金变动对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteMoneyChangeByIds(String ids) {
        return moneyChangeMapper.deleteMoneyChangeByIds(Convert.toStrArray(ids));
    }

    /**
     * 查询分润返佣明细 返回定义明细Vo
     *
     * @param moneyChangeVo
     * @return
     */
    @Override
    public List<MoneyChangeVo> selectMoneyChangeVoList(MoneyChangeVo moneyChangeVo) {
        return moneyChangeMapper.selectMoneyChangeVoList(moneyChangeVo);
    }

    /**
     * 申请体现列表
     *
     * @param moneyChange
     * @return
     */
    @Override
    public List<MoneyChange> applyMoneyList(MoneyChange moneyChange) {
        return moneyChangeMapper.applyMoneyList(moneyChange);
    }

    // app端公告列表
    @Override
    public AjaxResult selectMoneyChangeListByWhere() {
        List<AppMoneyChangeVo> list = moneyChangeMapper.selectMoneyChangeListByWhere();
        if (list == null) {
            return AjaxResult.error(1, "获取公告列表失败！");
        }
        return AjaxResult.successAndData("获取公告列表成功", list);
    }

    // app端利润:返回今日利润 昨日利润的总额，本月分润总额
    @Override
    public AjaxResult selectTodayProfitByMerchantId(String merchantNo) {
        if (StringUtils.isEmpty(merchantNo)) {
            return AjaxResult.error(1, "获取今日分润失败：缺失参数！");
        }
        Merchant merchant = merchantMapper.selectMerchantByMerchantNo(merchantNo);
        if (merchant == null) {
            return AjaxResult.error(2, "该用户不存在");
        }
        BigDecimal todayTrxAmt = moneyChangeMapper.selectTodayProfitByMerchantId(merchantNo, merchant.getId());
        BigDecimal yesterdayTrxAmt = moneyChangeMapper.selectYesterdayProfitByMerchantId(merchantNo, merchant.getId());
        BigDecimal monthTrxAmt = moneyChangeMapper.selectMonthTrxAmtProfitByMerchantId(merchantNo, merchant.getId());
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("todayTrxAmt", todayTrxAmt);
        map.put("yesterdayTrxAmt", yesterdayTrxAmt);
        map.put("monthTrxAmt", monthTrxAmt);
        return AjaxResult.successAndData("获取分润成功！", map);
    }

    // 今日或昨日利润列表
    @Override
    public AjaxResult profitDetails(String merchantNo, String type, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantNo) || StringUtils.isEmpty(type)) {
            return AjaxResult.error(1, "获取利润详情失败：缺失参数");
        }
        Merchant merchant = merchantMapper.selectMerchantByMerchantNo(merchantNo);
        if (merchant == null) {
            return AjaxResult.error(2, "该用户不存在");
        }
        List<ProfitVo> list = moneyChangeMapper.selectMoneyChangeListByUserIdAndDate(merchantNo, merchant.getId(), type,
                pageNum * pageSize, pageSize);
        return AjaxResult.successAndData("获取利润详情成功", list);
    }

    // app端 提现记录
    @Override
    public AjaxResult selectCashWithdrawalList(String merchantId, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "获取提现记录失败：缺失参数");
        }
        List<Map<String, Object>> list = moneyChangeMapper.selectCashWithdrawalList(merchantId, pageNum * pageSize,
                pageSize);
        return AjaxResult.successAndData("获取提现记录成功", list);
    }

    //// app端 根据月份统计利润：刷卡/办卡/贷款
    @Override
    public AjaxResult selectProfitByMonth(String merchantNo, String merchantId, String month) {
        if (StringUtils.isEmpty(merchantNo) || StringUtils.isEmpty(month) || StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "缺失参数");
        }
        List<Map<String, Object>> map = moneyChangeMapper.selectTotalMoneyByMonth(merchantNo, merchantId, month);
        return AjaxResult.successAndData("成功", map);
    }

    // 分享 ：收益详情列表
    @Override
    public AjaxResult selectProfitDetailsList(String merchantId, String merchantNo, String searchMonth, Integer pageNum,
                                              Integer pageSize) {
        if (StringUtils.isEmpty(merchantNo) || StringUtils.isEmpty(searchMonth) || StringUtils.isEmpty(merchantId)
                || pageNum == null || pageSize == null) {
            return AjaxResult.error(1, "缺失参数");
        }
        Map<String, Object> map = new HashMap<>(16);
        List<Map<String, Object>> list = moneyChangeMapper.selectProfitDetailsList(merchantId, merchantNo, searchMonth,
                pageNum * pageSize, pageSize);
        map.put("list", list); // 收益列表
        return AjaxResult.successAndData("获取收益详情成功", map);
    }

    @Override
    public AjaxResult selectProfitDetailsListByShopping(String merchantId, String merchantNo, String searchMonth,
                                                        Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantNo) || StringUtils.isEmpty(searchMonth) || StringUtils.isEmpty(merchantId)
                || pageNum == null || pageSize == null) {
            return AjaxResult.error(1, "缺失参数");
        }
        Map<String, Object> map = new HashMap<>(16);
        List<Map<String, Object>> list = moneyChangeMapper.selectProfitDetailsListByShopping(merchantId, merchantNo,
                searchMonth, pageNum * pageSize, pageSize);
        BigDecimal totalRevenue = moneyChangeMapper.selectTotalRevenueByMonthAndShopping(merchantId, searchMonth);// 收益总额
        map.put("list", list); // 收益列表
        map.put("totalRevenue", totalRevenue); // 收益总额
        return AjaxResult.successAndData("获取收益详情成功", map);
    }

    /**
     * 后台订单分润交易流水
     *
     * @param moneyChangeVo
     * @return
     */
    @Override
    public List<MoneyChangeNewOederVo> selectMoneyChangeVoListByNewOrder(MoneyChangeNewOederVo moneyChangeVo) {
        return moneyChangeMapper.selectMoneyChangeVoListByNewOrder(moneyChangeVo);
    }

    /**
     * 后台统计分润金额 和笔数
     *
     * @param moneyChangeVo
     * @return
     */
    @Override
    public Map<String, Object> selectCountMoneyChange(MoneyChangeNewOederVo moneyChangeVo) {
        return moneyChangeMapper.selectCountMoneyChange(moneyChangeVo);
    }

    /**
     * 后台升级分润列表
     *
     * @param upgradeVo
     * @return
     */
    @Override
    public List<MoneyChangeNewOederVo> selectMoneyChangeVoListByUpgrade(MoneyChangeNewOederVo upgradeVo) {
        return moneyChangeMapper.selectMoneyChangeVoListByUpgrade(upgradeVo);
    }

    /**
     * 后台统计升级的分润笔数和金额
     *
     * @param upgradeVo
     * @return
     */
    @Override
    public Map<String, Object> selectCountMoneyChangeByUpgrade(MoneyChangeNewOederVo upgradeVo) {
        return moneyChangeMapper.selectCountMoneyChangeByUpgrade(upgradeVo);
    }

    // //根据用户id 和分润类型统计总金额
    @Override
    public BigDecimal selectTotalByMerchantIdAndMoneyType(String merchantId, String moneyType) {
        return moneyChangeMapper.selectTotalByMerchantIdAndMoneyType(merchantId, moneyType);
    }

    /**
     * 分润计算
     *
     * @param orderType
     * @param amountMoney
     * @param merid
     */
    @Override
    public void commissions(String orderId, Integer orderType, BigDecimal amountMoney, String merid,
                            BigDecimal profitMoney) {
        /******************** 获取费率配置开始 **********************/
        LOGGER.info("开始清分，订单ID={}", orderId);
        String commission = "";
        try {
            commission = RedisPoolUtil.get("commission");
        } catch (Exception e) {
            commission = "nil";
        }
        if (commission == null || "nil".equals(commission)) {
            SystemConfig config = configMapper.selectSystemConfigByConfigCode("commission");
            RedisPoolUtil.setex("commission", config.getConfigValue(), 86400);
            commission = config.getConfigValue();
        }
        JSONObject jsonConfig = JSONObject.parseObject(commission);
        boolean isTryVip = jsonConfig.getBooleanValue("isTryVip");
        /******************** 获取费率配置开始 **********************/
        // 分润比例配置
        JSONObject profit = new JSONObject();
        // 最低费率结算底价
        BigDecimal minLowPriceRate = null;
        String[] lowPrice = null;
        // 平台费率结算底价
        BigDecimal lowPriceRate = null;
        // 共可分润多少手续费
        BigDecimal totalRate = null;

        // 平台笔数结算底价
        BigDecimal lowPricePro = null;
        // 最低笔数结算底价
        BigDecimal minLowPricePro = null;
        // 共可分润多少笔数费
        BigDecimal totalPro = null;
        String moenyType = "";
        if (orderType.equals(0) || orderType.equals(11)) {
            // 无卡消费
            moenyType = "10A";
            // 费率配置
            profit = jsonConfig.getJSONObject("wkProfit");
            // 获取平台费率配置
            lowPrice = profit.getString("rate").split("\\+");
            // 获取最低结算手续费
            minLowPriceRate = new BigDecimal(profit.getString("min").split("\\+")[0]);
            // 平台结算费率
            lowPriceRate = new BigDecimal(lowPrice[0]);
            // 计算可分润手续费
            totalRate = lowPriceRate.subtract(minLowPriceRate);
        } else if (orderType == 1) {
            // 养卡消费
            moenyType = "10B";
            // 费率配置
            profit = jsonConfig.getJSONObject("ykProfit");
            // 获取平台费率配置
            lowPrice = profit.getString("rate").split("\\+");
            // 获取最低结算手续费
            minLowPriceRate = new BigDecimal(profit.getString("min").split("\\+")[0]);
            // 平台结算费率
            lowPriceRate = new BigDecimal(lowPrice[0]);
            // 计算可分润手续费
            totalRate = lowPriceRate.subtract(minLowPriceRate);
        } else if (orderType == 7) {
            // 全额消费
            moenyType = "10K";
            // 费率配置
            profit = jsonConfig.getJSONObject("qeProfit");
            // 获取平台费率配置
            lowPrice = profit.getString("rate").split("\\+");
            // 获取最低结算手续费
            minLowPriceRate = new BigDecimal(profit.getString("min").split("\\+")[0]);
            // 平台结算费率
            lowPriceRate = new BigDecimal(lowPrice[0]);
            // 计算可分润手续费
            totalRate = lowPriceRate.subtract(minLowPriceRate);
        } else if (orderType == 12) {
            //碰一碰 消费
            moenyType = "20A";
            if (new BigDecimal("1000").compareTo(amountMoney) == 0 || new BigDecimal("1000").compareTo(amountMoney) == 1) {
                profit = jsonConfig.getJSONObject("pypMinProfit");
            } else {
                profit = jsonConfig.getJSONObject("pypMaxProfit");
            }
            // 获取平台费率配置
            lowPrice = profit.getString("rate").split("\\+");
            // 获取最低结算手续费
            minLowPriceRate = new BigDecimal(profit.getString("min").split("\\+")[0]);
            // 获取最低结算笔数费
            minLowPricePro = new BigDecimal(profit.getString("min").split("\\+")[1]);
            // 平台结算费率
            lowPriceRate = new BigDecimal(lowPrice[0]);
            // 计算可分润手续费
            totalRate = lowPriceRate.subtract(minLowPriceRate);
            // 平台结算笔数费
            lowPricePro = new BigDecimal(lowPrice[1]);
            // 计算可分润笔数费
            totalPro = lowPricePro.subtract(minLowPricePro);
        }
        if (moenyType.equals("10A") || moenyType.equals("10B") || moenyType.equals("10K") || moenyType.equals("20A")) {
            commissionRate(orderId, moenyType, amountMoney, merid, minLowPriceRate, lowPriceRate,profit,
                    profitMoney, isTryVip,totalPro);
        }
    }

	/**
	 * 清分与交易量添加
	 *
	 * @param moenyType
	 * @param amountMoney
	 * @param merid
	 */
	public void commissionRate(String orderId, String moenyType, BigDecimal amountMoney, String merid,
			BigDecimal minLowPriceRate, BigDecimal lowPriceRate, JSONObject profit, BigDecimal profitMoney,
			boolean isTryVip,BigDecimal totalPro) {
		BigDecimal yibai = new BigDecimal(100);
		String phone = "";
		BigDecimal hashMoney = BigDecimal.ZERO;
		BigDecimal one = BigDecimal.ZERO;
		BigDecimal two = BigDecimal.ZERO;
		BigDecimal three = BigDecimal.ZERO;
		BigDecimal four = BigDecimal.ZERO;
		BigDecimal five = BigDecimal.ZERO;
		if (("10K").equals(moenyType)) {
			one = BigDecimal.valueOf(0.05);
			two = BigDecimal.valueOf(0.08);
			three = BigDecimal.valueOf(0.11);
			four = BigDecimal.valueOf(0.13);
			five = BigDecimal.valueOf(0.15);
		} else if (("10B").equals(moenyType)) {
			one = BigDecimal.valueOf(0.02);
			two = BigDecimal.valueOf(0.04);
			three = BigDecimal.valueOf(0.05);
			four = BigDecimal.valueOf(0.06);
			five = BigDecimal.valueOf(0.07);
		} else if (("10A").equals(moenyType)) {
			one = BigDecimal.valueOf(0.01);
			two = BigDecimal.valueOf(0.015);
			three = BigDecimal.valueOf(0.020);
			four = BigDecimal.valueOf(0.025);
			five = BigDecimal.valueOf(0.030);
		} else if (("20A").equals(moenyType)) {
			one = BigDecimal.valueOf(0.002);
			two = BigDecimal.valueOf(0.003);
			three = BigDecimal.valueOf(0.004);
			four = BigDecimal.valueOf(0.005);
			five = BigDecimal.valueOf(0.006);
		}
		while (true) {// 查找到最上级退出
			Merchant mer = new Merchant();
			if (phone.equals("")) {
				mer = merchantMapper.selectMerchantById(merid);
			} else {
				mer = merchantMapper.selectMerchantByPhone(phone);
			}
			if (mer == null) {
				CompanyMoneyChang moneyChang = new CompanyMoneyChang();
				moneyChang.setId(StringUtils.randomUUID());
				moneyChang.setEntryMoney(profitMoney);
				moneyChang.setProfitMoney(hashMoney);
				moneyChang.setMoney(profitMoney.subtract(hashMoney).setScale(3, BigDecimal.ROUND_DOWN));
				moneyChang.setOrderId(orderId);
				moneyChang.setCreateTime(new Date());
				companyMoneyChangMapper.insertCompanyMoneyChang(moneyChang);
				break;
			}
			MerchantWallet merchantWallet = merchantWalletMapper.selectMerchantWalletByMerId(mer.getId());
			/** 修改用户交易量 */
			if (moenyType.equals("10A")) {
				merchantWallet.setSkMonth(merchantWallet.getSkMonth().add(amountMoney));
				merchantWallet.setSkDay(merchantWallet.getSkDay().add(amountMoney));
			} else if (moenyType.equals("20A")) {
				merchantWallet.setPypMonth(merchantWallet.getPypMonth().add(amountMoney));
				merchantWallet.setPypDay(merchantWallet.getPypDay().add(amountMoney));
			} else {
				merchantWallet.setHkMonth(merchantWallet.getHkMonth().add(amountMoney));
				merchantWallet.setHkDay(merchantWallet.getHkDay().add(amountMoney));
			}
			Integer level = mer.getLevel();
			if (level.equals(1) && DateUtils.getNowDate().compareTo(mer.getRealNameTime()) == -1) {
				level = 2;
			}
			if (level > 1) {
				BigDecimal mLowPriceRate = new BigDecimal(profit.getString(level.toString()).split("\\+")[0]);
				BigDecimal moeny = BigDecimal.ZERO;
				if (level.equals(6)) {
					int num = merchantParentMapper.selectTeamNumByPhoneAndLevel(mer.getPhone(), mer.getLevel());
					if (num >= 6 && num <= 30) {
						mLowPriceRate = mLowPriceRate.subtract(one);
					} else if (num >= 31 && num <= 150) {
						mLowPriceRate = mLowPriceRate.subtract(two);
					} else if (num >= 151 && num <= 300) {
						mLowPriceRate = mLowPriceRate.subtract(three);
					} else if (num >= 301 && num <= 600) {
						mLowPriceRate = mLowPriceRate.subtract(four);
					} else if (num >= 601) {
						mLowPriceRate = mLowPriceRate.subtract(five);
					}
				}
				if (mLowPriceRate.compareTo(lowPriceRate) == -1) {
					moeny = amountMoney.multiply(lowPriceRate.subtract(mLowPriceRate).divide(yibai)).setScale(3,
							BigDecimal.ROUND_DOWN);
					lowPriceRate = mLowPriceRate;
				}
				// 收款笔数是否分润
				if (moenyType.equals("20A")) {
					BigDecimal mLowPricePro = new BigDecimal(
							profit.getString(mer.getLevel().toString()).split("\\+")[1]);
					if (totalPro.compareTo(BigDecimal.ZERO) == 1) {
						moeny = moeny.add(mLowPricePro);
						totalPro = totalPro.subtract(mLowPricePro);
					}
				}
				if (moeny.compareTo(BigDecimal.ZERO) == 1) {
					MoneyChange mChange = new MoneyChange();
					mChange.setId(StringUtils.randomUUID());
					mChange.setMoneyType(moenyType);// 消费
					mChange.setTrxAmt(moeny);
					mChange.setUserId(mer.getId());
					mChange.setPaymentOrderId(orderId);
					mChange.setStatus("10C");
					mChange.setCreateTime(new Date());
					merchantWallet.setTotalMoney(merchantWallet.getTotalMoney().add(moeny));
					merchantWallet.setProfit(merchantWallet.getProfit().add(moeny));
					merchantWallet.setProfitMoth(merchantWallet.getProfitMoth().add(moeny));
					merchantWallet.setBalanceMoney(merchantWallet.getBalanceMoney().add(moeny));
					moneyChangeMapper.insertMoneyChange(mChange);
					hashMoney = hashMoney.add(moeny);
					// 推送
					String msg = moenyTypeStatus(moenyType);
					try {
						pushAll(mer.getId(), moeny.toString(), orderId, msg, "");
					} catch (Exception e) {
						e.printStackTrace();
						LOGGER.error("极光推送失败,{}", e);
					}
				}
			}
			merchantWalletMapper.updateMerchantWallet(merchantWallet);
			/*********************** 推荐人开始分润 **************************/
			Merchant pmer = merchantMapper.selectMerchantByPhone(mer.getParentPhone());
			if (pmer == null) {
				CompanyMoneyChang moneyChang = new CompanyMoneyChang();
				moneyChang.setId(StringUtils.randomUUID());
				moneyChang.setEntryMoney(profitMoney);
				moneyChang.setProfitMoney(hashMoney);
				moneyChang.setMoney(profitMoney.subtract(hashMoney).setScale(3, BigDecimal.ROUND_DOWN));
				moneyChang.setOrderId(orderId);
				moneyChang.setCreateTime(new Date());
				companyMoneyChangMapper.insertCompanyMoneyChang(moneyChang);
				break;
			}
			MerchantWallet merchantWalletPmer = merchantWalletMapper.selectMerchantWalletByMerId(pmer.getId());
			/** 修改用户交易量 */
			if (moenyType.equals("10A")) {
				merchantWalletPmer.setSkMonth(merchantWalletPmer.getSkMonth().add(amountMoney));
				merchantWalletPmer.setSkDay(merchantWalletPmer.getSkDay().add(amountMoney));
			} else if (moenyType.equals("20A")) {
				merchantWalletPmer.setPypMonth(merchantWalletPmer.getPypMonth().add(amountMoney));
				merchantWalletPmer.setPypDay(merchantWalletPmer.getPypDay().add(amountMoney));
			} else {
				merchantWalletPmer.setHkMonth(merchantWalletPmer.getHkMonth().add(amountMoney));
				merchantWalletPmer.setHkDay(merchantWalletPmer.getHkDay().add(amountMoney));
			}
			Integer parentLevel = pmer.getLevel();
			if (parentLevel.equals(1) && DateUtils.getNowDate().compareTo(pmer.getRealNameTime()) == -1) {
				parentLevel = 2;
			}
			if (parentLevel > 1) {
				BigDecimal pmLowPriceRate = new BigDecimal(profit.getString(parentLevel.toString()).split("\\+")[0]);
				BigDecimal pmoeny = BigDecimal.ZERO;
				if (parentLevel.equals(6)) {
					int num = merchantParentMapper.selectTeamNumByPhoneAndLevel(pmer.getPhone(), pmer.getLevel());
					if (num >= 6 && num <= 30) {
						pmLowPriceRate = pmLowPriceRate.subtract(one);
					} else if (num >= 31 && num <= 150) {
						pmLowPriceRate = pmLowPriceRate.subtract(two);
					} else if (num >= 151 && num <= 300) {
						pmLowPriceRate = pmLowPriceRate.subtract(three);
					} else if (num >= 301 && num <= 600) {
						pmLowPriceRate = pmLowPriceRate.subtract(four);
					} else if (num >= 601) {
						pmLowPriceRate = pmLowPriceRate.subtract(five);
					}
				}
				if (pmLowPriceRate.compareTo(lowPriceRate) == -1) {
					BigDecimal rateNow = lowPriceRate.subtract(pmLowPriceRate).divide(yibai);
					pmoeny = amountMoney.multiply(rateNow).setScale(3, BigDecimal.ROUND_DOWN);
					lowPriceRate = pmLowPriceRate;
				}
				// 收款笔数是否分润
				if (moenyType.equals("20A")) {
					BigDecimal mLowPricePro = new BigDecimal(
							profit.getString(pmer.getLevel().toString()).split("\\+")[1]);
					if (totalPro.compareTo(BigDecimal.ZERO) == 1) {
						pmoeny = pmoeny.add(mLowPricePro);
						totalPro = totalPro.subtract(mLowPricePro);
					}
				}
				if (pmoeny.compareTo(BigDecimal.ZERO) == 1) {
					MoneyChange mChange = new MoneyChange();
					mChange.setId(StringUtils.randomUUID());
					mChange.setMoneyType(moenyType);// 消费
					mChange.setTrxAmt(pmoeny);
					mChange.setUserId(pmer.getId());
					mChange.setPaymentOrderId(orderId);
					mChange.setStatus("10C");
					mChange.setCreateTime(new Date());
					merchantWalletPmer.setTotalMoney(merchantWalletPmer.getTotalMoney().add(pmoeny));
					merchantWalletPmer.setProfit(merchantWalletPmer.getProfit().add(pmoeny));
					merchantWalletPmer.setProfitMoth(merchantWalletPmer.getProfitMoth().add(pmoeny));
					merchantWalletPmer.setBalanceMoney(merchantWalletPmer.getBalanceMoney().add(pmoeny));
					moneyChangeMapper.insertMoneyChange(mChange);
					hashMoney = hashMoney.add(pmoeny);
					// 推送
					String msg = moenyTypeStatus(moenyType);
					// 推送
					try {
						pushAll(pmer.getId(), pmoeny.toString(), orderId, msg, "");
					} catch (Exception e) {
						e.printStackTrace();
						LOGGER.error("极光推送失败,{}", e);
					}

				}
			}
			// 修改上级分润金额
			merchantWalletMapper.updateMerchantWallet(merchantWalletPmer);
			phone = pmer.getParentPhone();
		}
		paymentOrderMapper.updateOrderStatusAndClearingStatus(orderId, 1, 1);
	}

    /**
     * 积分明细列表 商城积分兑换/充值分润
     *
     * @param merchantId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public AjaxResult selectShoppingScoreList(String merchantId, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantId) || pageNum == null || pageSize == null) {
            return AjaxResult.error(1, "缺失必要参数");
        }
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error(2, "该用户不存在");
        }
        Map<String, Object> map = new HashMap<>(16);
        List<MoneyChange> moneyChangeList = moneyChangeMapper.selectShoppingScoreList(merchantId, pageNum * pageSize,
                pageSize);
        map.put("moneyChangeList", moneyChangeList);
        // 当前积分
        map.put("shoppingScore", "");
        return AjaxResult.successAndData("获取积分明细成功", map);
    }

    /**
     * 积分兑换成功 》详情
     *
     * @param merchantId
     * @param orderId
     * @return
     */
    @Override
    public AjaxResult shoppingExchangeCashDetails(String merchantId, String orderId) {
        if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(1, "缺失必要参数");
        }
        PaymentOrder order = paymentOrderMapper.selectPaymentOrderById(orderId);
        if (order == null) {
            return AjaxResult.error(2, "获取订单信息失败，请咨询客服人员！");
        }
        ShoppingProduct product = shoppingProductMapper.selectShoppingProductByNumberNo(order.getAcqOrderNo());
        if (product == null) {
            return AjaxResult.error(2, "该商品不存在或已下架，请咨询客服人员！");
        }
        Map<String, String> map = new HashMap<>(16);
        map.put("productName", product.getProductName());
        map.put("img", product.getImg());
        map.put("showScore", product.getShowScore().toString());
        map.put("price", product.getPrice().toString());

        map.put("createDate", DateUtils.dateTime1(order.getCompleteTime()));

        return AjaxResult.successAndData("获取详情成功", map);
    }

    @Override
    public AjaxResult profitDetailsByShopping(String merchantNo, String type, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantNo) || StringUtils.isEmpty(type)) {
            return AjaxResult.error(1, "获取利润详情失败：缺失参数");
        }
        Merchant merchant = merchantMapper.selectMerchantByMerchantNo(merchantNo);
        if (merchant == null) {
            return AjaxResult.error(2, "该用户不存在");
        }
        List<ProfitVo> list = moneyChangeMapper.profitDetailsByShopping(merchantNo, merchant.getId(), type,
                pageNum * pageSize, pageSize);
        return AjaxResult.successAndData("获取利润详情成功", list);
    }

    @Override
    public AjaxResult selectProfitList(String type, Integer pageNum, Integer pageSize, String merchantId) {
        if (StringUtils.isEmpty(type) || StringUtils.isEmpty(merchantId) || pageNum == null || pageSize == null) {
            return AjaxResult.error(1, "必要参数不能空");
        }
        return AjaxResult.successAndData("成功",
                moneyChangeMapper.selectProfitList(type, pageNum * pageSize, pageSize, merchantId));
    }

    @Override
    public void withdrawal(PaymentOrder paymentOrder) {
        // TODO Auto-generated method stub
        BigDecimal money = BigDecimal.ZERO;
        BigDecimal entryMoney = paymentOrder.getRateMoney().subtract(paymentOrder.getCostRateMoney());
        Merchant mer = merchantMapper.selectMerchantById(paymentOrder.getMerchantId());
        Merchant pmer = merchantMapper.selectByPhone(mer.getParentPhone());
        if (mer.getLevel().equals(6) && pmer.getLevel().equals(6)) {
            int num = merchantParentMapper.selectTeamNumByPhoneAndLevel(pmer.getPhone(), pmer.getLevel());
            if (num >= 6 && num <= 30) {
                money = paymentOrder.getAmountMoney().multiply(BigDecimal.valueOf(0.01)).setScale(3,
                        BigDecimal.ROUND_DOWN);
            } else if (num >= 31 && num <= 150) {
                money = paymentOrder.getAmountMoney().multiply(BigDecimal.valueOf(0.02)).setScale(3,
                        BigDecimal.ROUND_DOWN);
            } else if (num >= 151 && num <= 300) {
                money = paymentOrder.getAmountMoney().multiply(BigDecimal.valueOf(0.03)).setScale(3,
                        BigDecimal.ROUND_DOWN);
            } else if (num >= 301 && num <= 600) {
                money = paymentOrder.getAmountMoney().multiply(BigDecimal.valueOf(0.04)).setScale(3,
                        BigDecimal.ROUND_DOWN);
            } else if (num >= 601) {
                money = paymentOrder.getAmountMoney().multiply(BigDecimal.valueOf(0.05)).setScale(3,
                        BigDecimal.ROUND_DOWN);
            }
            if (money.compareTo(BigDecimal.ZERO) == 1) {
                int i = merchantWalletMapper.increaseInRevenue(pmer.getId(), money);
                if (i > 0) {
                    saveMoenyChange(money, paymentOrder.getId(), pmer.getId(), MoneyTypeStatus.M.getCode(), "10C");
                    String msgS = "提现";
                    String msgE = "管理收益";
                    try {
                        pushAll(pmer.getId(), money.toString(), paymentOrder.getId(), msgS, msgE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOGGER.error("极光推送失败,{}",e);
                    }
                }
            }
        }
        CompanyMoneyChang moneyChang = new CompanyMoneyChang();
        moneyChang.setId(StringUtils.randomUUID());
        moneyChang.setEntryMoney(entryMoney);
        moneyChang.setProfitMoney(money);
        moneyChang.setMoney(entryMoney.subtract(money).setScale(3, BigDecimal.ROUND_DOWN));
        moneyChang.setOrderId(paymentOrder.getId());
        moneyChang.setCreateTime(new Date());
        companyMoneyChangMapper.insertCompanyMoneyChang(moneyChang);
    }

    private void saveMoenyChange(BigDecimal moeny, String orderId, String userId, String moenyType, String status) {
        MoneyChange m = new MoneyChange();
        m.setCreateTime(new Date());
        m.setId(StringUtils.randomUUID());
        m.setMoneyType(moenyType);
        m.setPaymentOrderId(orderId);
        m.setStatus(status);
        m.setUserId(userId);
        m.setTrxAmt(moeny);
        moneyChangeMapper.insertMoneyChange(m);
    }

    @Override
    public AjaxResult newProfitList(Integer pageNum, Integer pageSize, String merchantId, String time, String timeEnd) {
        if (StringUtils.isEmpty(merchantId) || pageNum == null || pageSize == null) {
            return AjaxResult.error(1, "必要参数不能空");
        }
        return AjaxResult.successAndData("成功",
                moneyChangeMapper.selectNewProfitList(pageNum * pageSize, pageSize, merchantId, time, timeEnd));
    }

    @Override
    public List<MoneyChange> selectListByMoneyTypeAndStutas(String merchantId, String moneyType, String status) {
        return moneyChangeMapper.selectListByMoneyTypeAndStutas(merchantId, moneyType, status);
    }


    /**
     * 分润推送
     */
    protected void pushAll(String merchantId, String money, String orderId, String msgS, String msgE) {
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderById(orderId);
        String name = paymentOrder.getMerchantName().substring(0, 1);
        Map<String, String> parm = new HashMap<String, String>(16);
        parm.put("id", merchant.getMerchantNo());
        parm.put("msg", name + "**" + msgS + paymentOrder.getAmountMoney() + "," + msgE + "分润" + money);
        parm.put("dateTime", DateUtils.getTime());
        JPushUtil.jpushAll(parm);
    }


    private String moenyTypeStatus(String moenyType) {
        if (moenyType.equals("20A")) {
            moenyType = "收款金额";
        } else if (moenyType.equals("20A")) {
            moenyType = "还款消费金额";
        } else if (moenyType.equals("10K")) {
            moenyType = "全额消费金额";
        } else if (moenyType.equals("20A")) {
            moenyType = "碰一碰消费";
        }else {
            moenyType="";
        }
        return moenyType;
    }

}
